package unit8.part5;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

public class ListenerTest {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("测试监听器");
        jFrame.setBounds(100, 100, 500, 500);

        JPanel panel = new JPanel();
        JButton buttonA = new JButton("按钮A");
        buttonA.setActionCommand("A");
        panel.add(buttonA);
        JButton buttonB = new JButton("按钮B");
        buttonB.setActionCommand("B");
        panel.add(buttonB);
        jFrame.add(panel, BorderLayout.NORTH);

        Vector<String> vector = new Vector<>();
        JList<String> list = new JList<>(vector);
        jFrame.add(list);

        JTextField field = new JTextField();
        jFrame.add(field, BorderLayout.SOUTH);

        ActionListener actionListener = e -> {
            e.getSource();// 来源
            String ac = e.getActionCommand();// 标识
            JOptionPane.showMessageDialog(null, "按钮" + ac + "点击事件触发");
        };

        ActionListener actionListener2 = e -> {
            e.getSource();// 来源
            String ac = e.getActionCommand();// 标识
            JOptionPane.showMessageDialog(null, "再次提醒");
        };

        MouseListener mouseListener = new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {

            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                Component component = (Component) e.getSource();
                component.setBackground(Color.RED);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                Component component = (Component) e.getSource();
                component.setBackground(null);
            }
        };

        KeyListener keyListener = new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                vector.add(KeyEvent.getKeyText(e.getKeyCode()));
                list.setListData(vector);
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        };
        buttonA.addActionListener(actionListener);// 一个监听器可以监听多个监听源
        buttonB.addActionListener(actionListener);
        buttonA.addMouseListener(mouseListener);// 一个监听源可以有多个监听器
        field.addKeyListener(keyListener);// 监听源 与 事件服务方法中处理的组件 不一定是一个组件

        jFrame.setVisible(true);
    }
}
